package com.huan.atm;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.log4j.Logger;

import java.io.PrintWriter;
import java.lang.reflect.Type;
import java.net.Socket;
import java.util.Scanner;

public class AtmClient {
    private static Logger logger = Logger.getLogger(AtmClient.class);
    public static void main(String[] args) {
        String host = "localhost";
        int port = 10020;
        //创建一个socket
        Scanner scanner = new Scanner(System.in);
        boolean f = true;
        try(
                Socket socket = new Socket(host,port);
                PrintWriter writer = new PrintWriter(socket.getOutputStream());
                Scanner in = new Scanner(socket.getInputStream());
                ){
            logger.info("连接ATM服务器"+socket.getLocalAddress()+"成功");
            do {
                System.out.println("请输入操作：1.查询余额 2.存款 3.取款 4.退出 5.错误指令");
                System.out.println("--------------------------------");
                String str = scanner.nextLine();
                String respond = null;
                if ("1".equalsIgnoreCase(str)){
                    writer.println("BALANCE 1");
                }else if ("2".equalsIgnoreCase(str)){
                    writer.println("DEPOSIT 1 100");
                }else if ("3".equalsIgnoreCase(str)){
                    writer.println("WITHDRAW 1 100");
                }else if ("5".equalsIgnoreCase(str)){
                    writer.println("ajdkjfdk");
                }else {
                    writer.println("QUIT");
                    writer.flush();
                    f = false;
                    break;
                }
                writer.flush();
                //获取服务器的响应
                respond = in.nextLine();
                System.out.println("服务器的响应:"+respond);
                Gson gson = new Gson();
                //设定gson处理的字符串数据的模板 vue axios
                Type type = new TypeToken<JsonModel<BankAccount>>(){}.getType();
                JsonModel<BankAccount> jsonModel = gson.fromJson(respond,type);
                if (jsonModel.getCode() == 1){
                    BankAccount bankAccount = jsonModel.getObj();
                    System.out.println("账户："+bankAccount.getId()+", 余额："+bankAccount.getBalance());
                }else {
                    System.out.println(jsonModel.getErrorMsg());
                }
            }while (f);
            System.out.println("ATM客户端退出");
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
